package com.sccl.iottm.action;

import com.sccl.iottm.entity.User;
import com.sccl.iottm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Dave
 * @Date 2018/9/6
 * @Description
 */
@Controller
@RequestMapping(value = "/user/*")
public class UserAction {
    @Value("${machine}")
    private String machine;
    @Autowired
    private UserService userService;
    @Autowired
    private SessionRegistry sessionRegistry;

    @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Map<String, String> toLogin(@RequestBody User user) {
        User u = userService.findUser(user.getName(), user.getPassword());
        Map<String, String> msg = new HashMap<>();
        System.out.println(user);
        msg.put("code", "0");
        if (u == null) {
            msg.put("code", "1");
            msg.put("msg", "账号密码错误");
        }
        msg.put("data", "gggggg");


        String id[] = {"3", "5"};

        List<Integer> collect = Arrays.stream(id)
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        return msg;
    }

    @PreAuthorize(value = "hasAnyAuthority('admin,dba')")
    @RequestMapping(value = "add", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String addUser(@RequestBody User user) {
        userService.addUser(user);
        return "ok";
    }

    @RequestMapping(value = "find", method = RequestMethod.GET)
    @ResponseBody
    public User addUser(String user) {
        return userService.findUserByName(user);
    }


    @RequestMapping(value = "getSession", method = RequestMethod.GET)
    @ResponseBody
    public String getSession(String user) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<SessionInformation> allSessions = sessionRegistry.getAllSessions(principal, true);
        String sessionId = allSessions.get(0).getSessionId();
        return "机器：" + machine + " SESSIONID:" + sessionId;
    }

}
